<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {
    public function login(){
       $this->display();
    }
    public function do_login(){
      $rules=array(
		     array('verify','require','验证码必须！'), 
		     array('username','require','用户名必须！'), 
		     array('password','require','密码必须！'), 
		     );

				 $User = M("user"); // 实例化User对象
		if (!$User->validate($rules)->create()){
		     // 如果创建失败 表示验证没有通过 输出错误提示信息
		     $this->error($User->getError());
		}else{
			$verify = new \Think\Verify();
			if(!$verify->check(I('post.verify'))){
				$this->error('验证码不正确');
			}
		     $user=M('user')->where(array(
		     	'username'=>I('post.username'),
		     	'password'=>md5(I('post.password')),
		     	))->find();
		     if(!$user){
		     	$this->error('账户名密码不正确');
		     }
		     $_SESSION['user_is_login']=true;
		     $_SESSION['user_name']=$user['username'];
		     $_SESSION['user_id']=$user['id'];
		     $this->redirect('front/index');
		}
    }
    public function regedit(){
    	$this->display();
    }
    public function do_regedit(){
      $rules=array(
		     array('verify','require','验证码必须！'), 
		     array('username','require','用户名必须！'), 
		     array('password','require','密码必须！'), 
		     array('password_repeat','password','确认密码不正确',0,'confirm'), // 验证确认密码是否和密码一致
		     );

				 $User = M("user"); // 实例化User对象
		if (!$User->validate($rules)->create()){
		     // 如果创建失败 表示验证没有通过 输出错误提示信息
		     $this->error($User->getError());
		}else{
			$verify = new \Think\Verify();
			if(!$verify->check(I('post.verify'))){
				$this->error('验证码不正确');
			}
		     $user=M('user')->where(array(
		     	'username'=>I('post.username'),
		     	))->find();
		     if($user){
		     	$this->error('账户名已存在');
		     }
			$User = M("user"); // 实例化User对象
			$data['username'] =I('post.username');
			$data['password'] =md5(I('post.password'));// 写入数据库
			$data['create_time']=time();
			$User->add($data);
		    $this->success('注册成功，请登录','login');
		}
    }

    public function Verify(){
    	$Verify = new \Think\Verify();
    	$Verify->length=4;
    	$Verify->Zh= true; 
		$Verify->entry();
    }
    public function logout(){
    	session_destroy();
    	$this->redirect('front/index');
    }
}